var param = {}, formId = 'queryForm', url = "/openx/order/exceptionOrderService/listPage", exceptionOrderDetail = {};

var days = 30;
var intervalDays = 30;

//查询按钮触发
$.openx.query = function () {
    //查询验证时间区间
    var createStartTime = new Date($("#startTime").val().replace(/\-/g, "\/"));
    var createEndTime = new Date($("#endTime").val().replace(/\-/g, "\/"));
    if (createStartTime > createEndTime) {
        layer.msg('开始时间不能大于结束时间！');
        return false;
    }
    var outTradeCode = $("input[name='outTradeCode']").val();
    var receiverPhone = $("input[name='receiverPhone']").val();
    if (outTradeCode.trim() === '' && receiverPhone.trim() === '') {
        if (isNaN(createStartTime.getTime())) {
            layer.msg('开始时间不能为空！');
            return false;
        }
        if (isNaN(createEndTime.getTime())) {
            layer.msg('结束时间不能为空！');
            return false;
        }
        if (createStartTime.setDate(createStartTime.getDate() + intervalDays) < createEndTime) {
            layer.msg('选择的时间区间必须在' + intervalDays + '天以内');
            return false;
        }
    }
    var data = $.openx.getJsonObj(formId);
    param.queryForm = data;
    var equryTimeStamp = new Date();
    $.openx.tableRefresh(url + "?t=" + equryTimeStamp.getTime(), param);
}

//初始化时间
layui.use('laydate', function () {
    var laydate = layui.laydate;
    document.getElementById('startTime').value = laydate.now(-1) + ' 00:00:00';
    document.getElementById('endTime').value = laydate.now() + ' 23:59:59';

    var data = $.openx.getJsonObj(formId);

    if (data.startTime !== '') {
        data.startTime = data.startTime + " 00:00:00";
    }
    if (data.endTime !== '') {
        data.endTime = data.endTime + " 23:59:59";
    }
    param.queryForm = data;
    $.openx.initTable("table", url, param);

});

function resetForm() {
    $('#queryForm')[0].reset();
    var laydate = layui.laydate;
    $('#channelSelectsId').val(null).trigger('change');
    console.log(laydate.now().split(' ')[0]);
    document.getElementById('startTime').value = laydate.now(-1).split(' ')[0] + ' 00:00:00';
    document.getElementById('endTime').value = laydate.now().split(' ')[0] + ' 23:59:59';
    start.max = '2099-06-16';
    start.min = '1900-01-01';
    end.max = '2099-06-16';
    end.min = '1900-01-01';
    var data = $.openx.getJsonObj(formId);
    data.startTime = data.startTime + " 00:00:00";
    data.endTime = data.endTime + " 23:59:59";
    param.queryForm = data;
    $.openx.initTable("table", url + "?t=" + new Date().getTime(), param);
    //$.openx.query();
}


//查看订单详情
function showExceptionOrderDetail(row) {
    $X("/order/exceptionOrderService", "getDetail").callx({
        id: row.id,
        onResult: function (result) {
            layer.closeAll('loading')
            result.channelName = channelMap.get(result.topChannelCode)
            var receiver = result.receiver
            result.createTime = $.openx.formatDate(new Date(result.createTime))
            if (receiver) {
                result.receiverName = receiver.receiverName
                result.receiverPhone = receiver.receiverPhone
                result.address = (receiver.provinceName ? receiver.provinceName : "") + (receiver.cityName ? receiver.cityName : "") + (receiver.districtName ? receiver.districtName : "") + (receiver.detailAddress ? receiver.detailAddress : "")
            }

            laytpl($.openx.innerHtml('orderDetailTpl')).render(result, function (html) {
                $.openx.openLayer(null, '订单详情', html, true)
            });

            //当前订单详细对象
            exceptionOrderDetail = result;
            console.log(result);
        },
        onError: function (error) {

        }
    });
}

//*****************格式化代码**********************/
//格式化下单时间
function createTimeFormat(value, row) {
    return $.openx.formatDate(new Date(value));
}

function showAll(row) {
    layer.tips(row.reason, '#table a[id="' + row.outTradeCode + '"]', {
        tips: [4, '#78BA32'],
        area: ['auto', 'auto']
    });
}

function topChannelFormat(value, row) {
    return channelMap.get(value);
}

var start = {
    istime: true,
    format: 'YYYY-MM-DD hh:mm:ss',
    max: '2099-06-16',
    isclear: false,
    istoday: true,
    choose: function (datas) {
        end.min = datas; //开始日选好后，重置结束日的最小日期
        var date = new Date(datas.replace(/\-/g, "\/"));
        getDaysByMonth(date.getFullYear(), date.getMonth() + 1)
        date.setDate(new Date(date.getDate() + (days - 1)));
        end.max = DateToStr(date, 'max');

    }
};
var end = {
    istime: true,
    format: 'YYYY-MM-DD hh:mm:ss',
    max: '2099-06-16',
    isclear: false,
    istoday: true,
    choose: function (datas) {
        start.max = datas; //结束日选好后，重置开始日的最大日期
        var date = new Date(datas.replace(/\-/g, "\/"));
        getDaysByMonth(date.getFullYear(), date.getMonth());
        days = days > date.getDate() ? days : date.getDate();
        date.setDate(new Date(date.getDate() - (days - 1)));
        start.min = DateToStr(date, 'min');
    }
};

$("#startTime").on("click", function () {
    start.elem = this;
    laydate(start);
});
$("#endTime").on("click", function () {
    end.elem = this;
    laydate(end);
});

function DateToStr(date, flag) {
    var year = date.getFullYear();
    var month = (date.getMonth() + 1).toString();
    var day = (date.getDate()).toString();
    if (month.length == 1) {
        month = "0" + month;
    }
    if (day.length == 1) {
        day = "0" + day;
    }
//    var time='';
//    if(flag=='max'){time='23:59:59';}
//    if(flag=='min'){time='00:00:00';}
    dateTime = year + "-" + month + "-" + day;
    return dateTime;
}

//获取当前月多少天
function getDaysByMonth(year, month) {
    var monthDays;
    //判断月份大小获得天数
    if (month == '1' || month == '3' || month == '5' || month == '7' || month == '8' || month == '10' || month == '12') {
        monthDays = 31;
    } else if (month == '4' || month == '6' || month == '9' || month == '11') {
        monthDays = 30;
    } else {
        monthDays = 28;
        //判断当前选择的年份是否是闰年
        if ((year % 100 == 0 && year % 400 == 0) || year % 4 == 0) {
            monthDays = 29;
        }
    }
    days = monthDays;
    return days;
}

//乘法函数
function accMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length;
    } catch (e) {
    }
    try {
        m += s2.split(".")[1].length;
    } catch (e) {
    }
    // alert(Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m));
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

function formatStatus(value, row) {
    switch (value) {
        case "PENDING":
            return "待处理";
        case "FINISHED":
            return "已处理";
    }
}

function formatReason(value, row) {
    if (row.reason) {
        if (row.reason.length > 18) {
            return "<a id='" + row.outTradeCode + "' onclick='showAll(" + JSON.stringify(row) + ");'>" + row.reason.substring(0, 18) + "\n..." + "</a>";
        } else {
            return row.reason;
        }
    }
    return "-";
}

function showHandleFormat(value, row) {
    var isFinished = row.status === 'FINISHED';
    return "<a href=\'javascript:void(0)\' onclick =\'javascript:handleExceptionOrder(" + JSON.stringify(row) + ")\'><button type='button'" + (isFinished ? "disabled" : "") +" class='btn btn-outline " + (isFinished ? 'btn-default' : 'btn-primary') + " btn-xs'>处理完成</button> <a>";
}

function showDetail(value, row) {
    return "<a href=\'javascript:void(0)\' title='\点击查看详情\' style = '\color:#000000;text-decoration:underline;\' onclick =\'javascript:showExceptionOrderDetail(" + JSON.stringify(row) + ")\'><b>" + row.outTradeCode + "</b><a>";
}

function handleExceptionOrder(row) {
    laytpl($.openx.innerHtml('handleOrderTpl')).render(row, function (html) {
        $.openx.openLayer(['500', '250'], '单据备注', html, true, function () {
            var obj = $.openx.getJsonObj('handleExceptionOrderForm');
            if (obj.remark.trim() === '' || obj.remark.length === 0) {
                layer.msg("请输入处理情况说明");
                return;
            }
            if (obj.remark.length > 255) {
                layer.msg("最多填写255个字符");
                return;
            }
            $X("/order/exceptionOrderService", "updateStatus2Finish").callx({
                id: row.id,
                remark: obj.remark ? obj.remark : '',
                onResult: function (result) {
                    layer.msg("处理成功");
                    setTimeout(function () {
                        layer.closeAll();
                        $.openx.tableRefresh(null, null, true);
                    }, 1000);
                },
                onError: function (error) {
                    layer.msg(JSON.parse(error).message);
                }
            });
        })
    });
}